<template>
	<view class="load" v-if="!load">
		<u-loading-icon mode="circle" inactive-color="#fff" text="正在加载..." vertical></u-loading-icon>
	</view>
	<view v-else class="user_edit wap">

		<view class="group group_hd">
			<view class="lab"><!-- <view class="must">*</view> -->头像</view>
			<view class="inp_box">
				<button class="user_header_btn" open-type="chooseAvatar" hover-class="none" @chooseavatar="chooseavatar">
					<view class="user_headerimg">
						<view class="cover_btn">
							<image class="image_user" v-if="isHeader" @error="isHeader = false" :src="reqData.HeadImgUrl" mode="aspectFill" />
							<image class="iamge_icon" v-else src="@/static/img/hd.png" mode="" />
						</view>
						<uni-icons type="right" size="18" color="#c6c6c6"></uni-icons>
					</view>
				</button>
			</view>
		</view>
		<view class="group">
			<view class="lab"><!-- <text class="must">*</text> -->昵称</view>
			<view class="inp_box">
				<input type="nickname" maxlength="10" v-model="reqData.Name" placeholder="输入昵称(最多输入10个字)" />
			</view>
		</view>
		<view class="group group_bd">
			<view class="lab">手机号</view>
			<view class="inp_box">
				<input type="number" maxlength="11" v-model="reqData.Phone" placeholder="请输入手机号" />
				<!-- #ifdef MP-WEIXIN -->
				<button class="s_btn" open-type="getPhoneNumber" @getphonenumber="getNums">
					绑定手机
				</button>
				<!-- #endif -->
			</view>
		</view>
		<view class="group" @click="showBirthday = true">
			<view class="lab">生日</view>
			<view class="inp_box">
				<input type="text" disabled v-model="reqData.Birthday" placeholder="请选择生日日期" />
				<uni-icons type="right" size="18" color="#c6c6c6"></uni-icons>
			</view>
		</view>
		
		<view class="group" @click="nav_to('/pages/store/myHome_set?mold=1')">
			<view class="lab">地区</view>
			<view class="inp_box">
				<input type="text" disabled v-model="cityStr" placeholder="请选择地区" />
				<uni-icons type="right" size="18" color="#c6c6c6"></uni-icons>
			</view>
		</view>
		
		<!-- <view style="height: 160rpx;"></view> -->
		<view class="saveBox">
			<view class="btn saveBtn" @click="sub">保存</view>
		</view>
		
		
		<u-datetime-picker immediateChange ref="datetimePicker" @cancel="showBirthday = false" :show="showBirthday"
		:minDate="minDate" :maxDate="maxDate" mode="date" v-model="defaultDay" @confirm="setBirthday"></u-datetime-picker>
		<u-picker :show="showCity" @cancel="showCity = false" immediateChange ref="uPicker" :columns="cityList"
			@change="changeHandler" @confirm="setCity"></u-picker>
	</view>
</template>

<script>
	import address from './address.js';
	import { ieChooseImage,isCheckImage } from "../../common/imgExamine";
import { data } from 'uview-ui/libs/mixin/mixin.js';
	export default {
		components: {},
		data() {
			let d = new Date('1923/1/1');
			let day = new Date('2000/1/1').getTime();
			console.log(d);
			let nowD = new Date().getTime();
			return {
				load: false,
				cityStr: '',
				cityList: [],
				height: '', // 身高
				weight: '', // 体重
				showCity: false,
				defaultDay:day,
				nowDate: nowD,
				minDate: d.getTime(),
				maxDate: nowD,
				showBirthday: false,
				showIncome: false,
				showSex: false,
				user: {},
				isHeader: true,
				reqData: {
					Area:'',
					PlayFee: 0,
					IsFee: 0,
					IsOpenMember: '',
					Name: '',
					Phone: '',
					HeadImgUrl: '',
					Descript: '',
					GolfPoint: '',
					Sex: '',
					Province: '',
					City: '',
					Birthday: '',
					BgImg: '',
					UserImgs: '',
					WechatNo: '',
					Income: '',
					Height: '',
					Weight: '',
					IsAuditApplyWX:0,
				},
				tag:[]
			};
		},
		

		async onLoad() {
			let u = uni.getStorageSync('user');
			let res = await this.$api.post('User/GetUserInfo', {
				ID: u.UserID
			});
		
			this.user = res.data;
			for (let key in this.reqData) {
				this.reqData[key] = this.user[key] || '';
				if (key === 'Birthday' && this.user.Birthday) {
					let d = new Date(this.reqData[key]);
					this.reqData[key] = this.time = uni.$u.timeFormat(d.getTime(), 'yyyy-mm-dd');
				}
			}
			this.reqData.Name = this.$util.entitiesToUtf16(this.reqData.Name)
			this.reqData.Descript = this.$util.entitiesToUtf16(this.reqData.Descript)
			
			let add = address;
			console.log(add);
			let arr1 = add.map(item => item.name);
			let arr2 = add[0].children.map(item => {
				if (item.name == '市辖区' || item.name == '县') {
					return '--';
				} else {
					return item.name;
				}
			});
		
			this.cityList = [arr1, arr2];
			this.load = true;
		
			uni.$on('user_upload', async res => {
				// this.reqData.HeadImgUrl=res.url;
				// this.reqData.UserImgs=res.source;
				console.log(res, " '--------user_upload'");
				let r1 = await this.uploading(res.url);
				console.log(r1, " '--------r1'");
				let r2 = await this.uploading(res.source);
				console.log(r2, " '--------r1'")
				this.reqData.HeadImgUrl = r1;
				this.reqData.UserImgs = r2;
				
				this.reqData.Name = this.$util.entitiesToUtf16(this.reqData.Name)
				this.reqData.Descript = this.$util.entitiesToUtf16(this.reqData.Descript)
			})
			if(this.reqData.Birthday){
				this.nowDate = new Date(this.reqData.Birthday)
			}
			
			uni.$on('updateAddress',(data)=>{
				this.reqData.Area = data.Area
				this.reqData.City = data.City
				this.reqData.Province = data.Province
			})
		},
		async onShow() {
			let u = uni.getStorageSync('user');
			let res = await this.$api.post('User/GetUserInfo', {
				ID: u.UserID
			});
			
			this.user = res.data;
			if(res.data.Tag){
				this.tag = this.user.Tag.split(',')
			}else{
				this.tag = []
			}
		},
		onUnload() {
			uni.$off('user_upload')
			uni.$off('updateAddress')
		},
		watch: {
			'reqData.City': function(newVal) {
				this.cityStr = `${this.reqData.Province} ${this.reqData.City} ${this.reqData.Area}`;
			},
			reqData: {
				deep: true, //true为进行深度监听,false为不进行深度监听
				async handler(newVal) {
					let o = {};
					for (let key in newVal) {
						if (this.reqData[key] != '') {
							o[key] = this.reqData[key];
						}
					}
					// let res = await this.$api.post('User/Update', o);
				}
			}
		},
		methods: {
			inputrem(e){
				console.log(e);
				this.$nextTick(()=>{
					// const {value,cursor} = e.detail
					// let str = this.$util.utf16ToEntities(value) 
					let str = e
					if (str.length>200) {
						this.reqData.Descript = str.slice(0,200)
					}else{
						this.reqData.Descript = str
					}
				})
			},
			radioCheck(e){
				this.reqData.IsAuditApplyWX=e;
			},
			getNums(e) {
				let _this = this;

				uni.login({
					provider: 'weixin',
					success: async res => {
						let d = {
							encryptedData: e.detail.encryptedData,
							code: res.code,
							aesIv: e.detail.iv
						}
						let res3 = await _this.$api.post('User/GetPhoneNumber', d);

						_this.reqData.Phone = res3.data;

					},
					fail: err => {
						uni.showModal({
							content: '获取失败',
							showCancel: false
						});
					}
				});

			},
			lookImg(obj) {
				console.log(obj);
				let ind = 0;
				let lookList = this.localList.map((item, index) => {
					if (item.ID == obj.ID) {
						ind = index;
					}
					return {
						ID: item.ID,
						url: item.netPath || item.ImgPath
					};
				});
				let urlList = lookList.map(e => e.url);
				console.log(lookList, ind);

				uni.previewImage({
					current: ind,
					urls: urlList
				});
			},
			lookImg2(obj) {
				console.log(obj);
				let ind = 0;
				let lookList = this.oldImgeList.map((item, index) => {
					if (item.ID == obj.ID) {
						ind = index;
					}
					return {
						ID: item.ID,
						url: item.netPath || item.ImgPath
					};
				});
				let urlList = lookList.map(e => e.url);
				console.log(lookList, ind);

				uni.previewImage({
					current: ind,
					urls: urlList
				});
			},
			setHYFM(item) {
				this.reqData.UserImgs = item.netPath;
				setTimeout(() => {
					this.$pv.msg('设置成功!');
				}, 500);
			},
			setIncome(e) {
				this.reqData.Income = e.value[0];

				this.showIncome = false;
			},
			async setHD(item) {
				console.log(item.netPath);
				this.reqData.HeadImgUrl = item.netPath;
			},
			setIsOpenMember(e) {
				console.log(e);
				this.reqData.IsOpenMember = e ? 1 : 0;
			},
			setIsFee(e) {
				this.reqData.IsFee = e ? 1 : 0;
			},
			setUserImgs() {
				let _this = this;
				uni.chooseMedia({
					count: 1, //默认9
					mediaType: ['image'],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: async function(res) {
						console.log(res, '------look');
						let r = await _this.uploading(res.tempFiles[0].tempFilePath);
						_this.reqData.UserImgs = r;
					}
				});
			},
			setName(e) {
				
			},
			setPhone(e) {
				
			},
			async setBirthday(e) {
				console.log(e.value);
				this.reqData.Birthday = await uni.$u.date(e.value, 'yyyy-mm-dd');
				this.showBirthday = false;
			},
			setCity(e) {
				this.reqData.Province = e.value[0];
				if (e.value[1] === '--') {
					this.reqData.City = this.reqData.Province;
					this.cityStr = e.value[0];
				} else {
					this.reqData.City = e.value[1];
					this.cityStr = e.value[0] + ' ' + e.value[1];
				}
				this.showCity = false;
			},
			setSex(e) {
				this.reqData.Sex = e.value[0];
				this.showSex = false;
			},
			
			async chooseavatar(e) {
				console.log(e,'1111111');
				 try {
					let _this = this;
					let url = await this.uploadingList(e.detail.avatarUrl)
					console.log('==============',url);
					if (url) {
						_this.reqData.HeadImgUrl = url
						_this.isHeader = true;
					} else {
						uni.showToast({
							title: res[0]?.msg,
							icon: "none",
							duration: 2000,
						});
					}
				} catch (error) {
					this.$pv.msg("图片上传失败");
					console.log(error,'2222222');
				}
			},
			async uploadingList(url, tempKey, timeStamp) {
				this.$pv.load('正在上传');
				const r = await this.$upload(url,()=>{});
				
				this.$pv.closeLoad('')
				console.log('-----------',r);
				return r;
			},
			getNums(e) {
				let _this = this;
			
				uni.login({
					provider: 'weixin',
					success: async res => {
						let d = {
							encryptedData: e.detail.encryptedData,
							code: res.code,
							aesIv: e.detail.iv
						}
						let res3 = await _this.$api.post('User/GetPhoneNumber', d);
						if(res3.data){
							_this.reqData.Phone = res3.data;
							_this.$pv.msg('获取成功')
						}else{
							_this.$pv.msg('获取失败')
						}
			
					},
					fail: err => {
						uni.showModal({
							content: '获取失败',
							showCancel: false
						});
					}
				});
			
			},
			async sub() {
				let isTel = this.$util.checkPhone(this.reqData.Phone)
	
				if (!this.reqData.HeadImgUrl) {
					this.$pv.msg('请上传头像');
					return;
				}
				
				if (!this.reqData.Name) {
					this.$pv.msg('请输入昵称');
					return;
				}
				
				if(!isTel){
					this.$pv.msg('请输入正确的手机号码');
					return;
				}
				
				// this.reqData.UserImgs=this.reqData.HeadImgUrl;
				
				this.$pv.load('正在处理');
				let o = {};
				for (let key in this.reqData) {
					if (this.reqData[key] != '') {
						o[key] = this.reqData[key];
					}
				}
				o.Name = this.$util.utf16ToEntities(o.Name)
				let res = await this.$api.post('User/Update', o);
				this.$pv.closeLoad();
				this.$pv.msg('保存成功');
				this.nav_back(1000);
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				return value;
			},
			changeHandler(e) {
				console.log(e);
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				if (columnIndex === 0) {
					picker.setColumnValues(
						1,
						address[index].children.map(item => {
							if (item.name == '市辖区' || item.name == '县') {
								return '--';
							} else {
								return item.name;
							}
						})
					);
				}
			}
		},
		
	};
</script>

<style lang="scss">
	page{
		background-color: #f6f6f6;
	}
	button[plain] {
		border: 0
	}
	button::after{ border: none;} 
	.user_edit {
		padding-bottom: 32rpx;
		background: #fff;
		margin-top: 16rpx;
	}

	.tip {
		margin-top: 32rpx;
		height: 70rpx;
		background: #FFF7E0;
		border-radius: 4rpx;
		color: #E3A029;
		line-height: 70rpx;
		text-align: center;
	}

	.user_header_btn {
		width: 100%;
		display: flex;
		justify-content: flex-end;
		border-radius: 0;
		.user_headerimg{
			display: flex;
			align-items: center;
		}
	}

	.user_header,
	.cover_btn {
		border-radius: 10rpx;
		overflow: hidden;
		height: 100rpx;
		width: 100rpx;
		background: rgba(255, 255, 255, 0.1);
		margin-right: 16rpx;
		display: flex;
		// text-align: center;
		justify-content: center;
		align-items: center;

		.iamge_icon {
			height: 60rpx;
			width: 60rpx;
		}

		.image_user {
			height: 100%;
			width: 100%;
			border-radius: 50%;
		}
	}

	.lab {
		// height: 90rpx;
		// line-height: 90rpx;
		padding-right: 10rpx;
		color: #333333;
		font-size: 32rpx;
		display: flex;
	.must{
		color: #EF4034;
		font-size: 32rpx;
		margin-top: 7rpx;
	}
		.msg {
			display: inline-block;
			padding-left: 10rpx;
			font-size: 28rpx;
			color: #dd3232;
		}
	}
	
	.group {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		position: relative;

		&::after {
			position: absolute;
			bottom: 0;
			right: 0;
			left: 0;
			height: 2rpx;
			content: '';
			transform: scaleY(.6);
			background-color: #E4E4E4;
		}

		.inp_box {
			flex: 1;
			display: flex;
			align-items: center;
			flex-direction: row;
			justify-content: flex-end;

			input {
				width: 100%;
				text-align: right;
				padding: 32rpx 0;
				color: #333;
				font-size: 32rpx;
			}
			.inp_text{
				font-size: 32rpx;
				padding: 32rpx 0;
			}
			.radio_s{
				display: flex !important;
				height:100rpx;
			}
			.item_check {
				padding: 10rpx;
				display: flex;
				flex-direction: row;
				
				.desc{
					color:#000 !important;
				}
			}
		}
		.diyPadding{
			padding: 32rpx 0;
		}
		.icon_box {
			height: 40rpx;
			width: 40rpx;
			line-height: 40rpx;
		}

		.inp_append {
			margin-left: 8rpx;
		}

		.s_btn {
			color: #fff;
			    font-size: 24rpx;
			    width: 170rpx !important;
			    height: 60rpx !important;
			    border-radius: 5rpx;
			    background-color: #FF6030;
			    margin: 0 0 0 20rpx;
		}

	}
	
	.group_check {
		align-items: center;
		flex-wrap: wrap;
		position: relative;
		line-height: 90px;
		height: 190rpx;
		
		.inp_box_c {
			flex: 1;
			display: flex;			
			flex-direction: column;
			
			view{
				height:70rpx;
				color: #666666;
			}
		
			input {
				width: 100%;
				text-align: right;
			}
		}
	}
	.group_img {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		position: relative;
		line-height: 180rpx;

		&::after {
			position: absolute;
			bottom: 0;
			right: 0;
			left: 0;
			height: 2rpx;
			content: '';
			transform: scaleY(.6);
			background-color: #E4E4E4;
		}
		.wxlab {
			height: 60rpx;
			padding-right: 10rpx;
			color: #333333;
			font-size: 32rpx;
			line-height: 60rpx;
			.must{
				color: #EF4034;
				font-size: 32rpx;
			}
			.desc{
				color:#dc7e78;
				font-size: 28rpx;
			}
			.req_t {
				color:#ff557f !important;
			}
		}
		.inp_box {
			flex: 1;
			display: flex;
			align-items: center;

			input {
				padding: 32rpx 0;
				width: 100%;
				text-align: right;
			}
		}
		.inp_box_c {
			flex: 1;
			display: flex;			
			flex-direction: column;
			
			view{
				height:70rpx;
			}
		
			input {
				width: 100%;
				text-align: right;
			}
		}

	}
	.group_hd {
		height: auto;
		padding-bottom: 20rpx;
		padding-top: 20rpx;
	}
	
	.group_bd {
		border-bottom: none;
	}

	.m40 {
		margin-top: 50rpx;
	}

	.group_textarea {
		margin-top: 24rpx;
		flex: 1;
		height: 200rpx;
		padding-top: 12rpx;
		padding-left: 10rpx;
		padding-right: 10rpx;
		// border-style: none;
		border-radius: 16rpx;
		background-color: #F8F8F8;
		/deep/ .u-textarea {
			background: none !important;
			// border-bottom: none !important;
			// border-color: rgba(64, 64, 64, 1) !important;
			padding-left: 20rpx;
		}
		/deep/ .u-border{
			border: none;
		}
		/deep/ .u-textarea__count {
			background: none !important;
			color: #000 !important;
		}

		/deep/ .u-textarea__field {
			color: #000 !important;
		}
	}



	.inp_box_r {
		display: flex;
		justify-content: flex-end;
	}

	.text_r {
		text-align: right;
	}

	.group_warp {
		padding-bottom: 20rpx;
		display: block;
		height: auto;
	}

	.imgvideo {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;

		&::after {
			height: 1px;
			width: 220rpx;
			display: block;
			content: '';
		}

		.item {
			position: relative;
			margin-top: 15rpx;
			width: 220rpx;
			height: 220rpx;
			background: rgba(255, 255, 255, 0.1);
			border-radius: 16rpx;

			.pro {
				position: absolute;
				top: 50%;
				width: 100%;
				transform: translateY(-50%);
				text-align: center;
				color: #888;
			}

			image {
				height: 100%;
				width: 100%;
				border-radius: 16rpx;
			}

			.del_con {
				position: absolute;
				top: 0;
				right: 0;
				background: rgba(0, 0, 0, 0.4);
				height: 40rpx;
				width: 40rpx;
				text-align: center;
				line-height: 40rpx;
				border-radius: 0 16rpx 0 16rpx;
			}

			.bottomset {
				position: absolute;
				width: 100%;
				bottom: 0;
				left: 0;
				height: 50rpx;
				background: #404040;
				color: #fff;
				text-align: center;
				align-items: center;
				font-size: 24rpx;
				line-height: 50rpx;
				opacity: 0.7;
			}
		}

		.item_add {
			position: relative;

			&::before,
			&::after {
				display: block;
				content: '';
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				margin: auto;
				position: absolute;
				height: 40rpx;
				width: 8rpx;
				border-radius: 8rpx;
				background: #fff;
				border-radius: 10rpx;
			}

			&::before {
				transform: rotate(90deg);
			}
		}
	}

	.iamge_list_sm {
		margin-top: 10rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;

		.tit {
			width: 100%;
			line-height: 2;
		}

		.item {
			height: 90rpx;
			width: 90rpx;

			image {
				height: 100%;
				width: 100%;
			}
		}

		.more {
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 4rpx;
			background: rgba(254, 240, 188, 0.1);
		}
	}
	.saveBox{
		position: fixed;
		width: 100%;
		box-sizing: border-box;
		left: 0;
		bottom: 0;
		padding: 20rpx 40rpx 50rpx;
		background-color: #fff;
		.saveBtn{
			width: 100%;
			background: #FF6030;
			border-radius: 44rpx;
		}
	}
	
</style>